package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;

public class ReporteBitacora extends javax.swing.JInternalFrame {
    private JDatePickerImpl selector_fecha_inicial,selector_fecha_final;
    private DefaultListModel<ModeloItemValor> modelo = new DefaultListModel<ModeloItemValor>();
    private JCheckBox jchkFechaInicio,jchkFechaFinal;
    private JFileChooser selector;
    public ReporteBitacora() {
        initComponents();
        CargarFormularios();
        jcbFormulario.setSelectedIndex(-1);
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("reporte_bitacora.xls"));
        jlstUsuario.setModel(modelo);
        jchkFechaInicio=new JCheckBox("",true);
        jchkFechaFinal=new JCheckBox("",true);
        jchkFechaInicio.setToolTipText("Incluir");
        jchkFechaFinal.setToolTipText("Incluir");
        selector_fecha_inicial = Util.ColocarSelectorFecha(jpFechaInicial, null,new Component[]{jchkFechaInicio});
        selector_fecha_final = Util.ColocarSelectorFecha(jpFechaFinal, null,new Component[]{jchkFechaFinal});
        CardarDatos("");
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfUsuario = new javax.swing.JTextField();
        jScrollPane6 = new javax.swing.JScrollPane();
        jlstUsuario = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jpFechaFinal = new javax.swing.JPanel();
        jpFechaInicial = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jcbFormulario = new javax.swing.JComboBox();
        jchkFormulario = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblBitacora = new javax.swing.JTable();
        jbtnBuscar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblDetalleBitacora = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jbtnExportar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Reporte de Bitácora");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/reporte_bitacora.png"))); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel1.setText("Usuario:");

        jtfUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfUsuarioKeyTyped(evt);
            }
        });

        jScrollPane6.setViewportView(jlstUsuario);

        jLabel3.setText("Fecha Inicial:");

        jLabel4.setText("Fecha Final:");

        javax.swing.GroupLayout jpFechaFinalLayout = new javax.swing.GroupLayout(jpFechaFinal);
        jpFechaFinal.setLayout(jpFechaFinalLayout);
        jpFechaFinalLayout.setHorizontalGroup(
            jpFechaFinalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 168, Short.MAX_VALUE)
        );
        jpFechaFinalLayout.setVerticalGroup(
            jpFechaFinalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 23, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jpFechaInicialLayout = new javax.swing.GroupLayout(jpFechaInicial);
        jpFechaInicial.setLayout(jpFechaInicialLayout);
        jpFechaInicialLayout.setHorizontalGroup(
            jpFechaInicialLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 168, Short.MAX_VALUE)
        );
        jpFechaInicialLayout.setVerticalGroup(
            jpFechaInicialLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 23, Short.MAX_VALUE)
        );

        jLabel5.setText("Formulario:");

        jchkFormulario.setToolTipText("Incluir");

        jtblBitacora.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblBitacoraMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtblBitacora);

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar_mini.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jtblDetalleBitacora);

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(33, 33, 33)
                                .addComponent(jtfUsuario))
                            .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel5)
                                    .addGap(18, 18, 18)
                                    .addComponent(jcbFormulario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jchkFormulario))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jpFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addGap(18, 18, 18)
                                    .addComponent(jpFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jpFechaInicial, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(15, 15, 15)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jpFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel5)
                                        .addComponent(jcbFormulario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jchkFormulario))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void CargarFormularios(){
        Util.CargarJComboBox(jcbFormulario,"SELECT DISTINCT formulario,formulario FROM bitacora",new String[]{"formulario","formulario"});
    }
    private void CardarDatos(String filtro){
        String consulta="SELECT b.id_bitacora,CONCAT_WS(' ',u.nombre,u.apellido),u.identidad,DATE_FORMAT(b.fecha_acceso,'%d/%m/%Y'),"
                +"DATE_FORMAT(b.fecha_clausura,'%d/%m/%Y'),b.formulario FROM bitacora b INNER JOIN usuario u ON b.id_usuario=u.id_usuario"+filtro
                +" ORDER BY b.id_bitacora ASC";
        Util.CargarTabla(jtblBitacora,consulta,new String[]{"ID","Usuario","N° Identidad","Fecha Acceso","Fecha Clausura","Formulario"});
        Util.AlinearColumnas(jtblBitacora,SwingConstants.CENTER);
        Util.OcultarColumna(jtblBitacora,0);
    }
    private void CargarDatosDetalle(String id){
        String consulta="SELECT accion,hora FROM detallebitacora WHERE id_bitacora="+id+" ORDER BY hora ASC;";
        Util.CargarTabla(jtblDetalleBitacora,consulta,new String[]{"Acción","Hora"});
        Util.AlinearColumnas(jtblDetalleBitacora,SwingConstants.CENTER);
    }
    private void ConsultaFiltrada(){
        String filtro="";
        filtro=(jlstUsuario.getSelectedIndex()>-1?" WHERE u.id_usuario="+((ModeloItemValor)jlstUsuario.getSelectedValue()).getValor():"");
        filtro+=(jchkFormulario.isSelected()?(filtro.equals("")?" WHERE":" AND")+" formulario='"+jcbFormulario.getSelectedItem().toString()+"'":"");
        if(jchkFechaInicio.isSelected()||jchkFechaFinal.isSelected()){
            SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
            if(jchkFechaInicio.isSelected())
                filtro+=(filtro.equals("")?" WHERE":" AND")+" b.fecha_acceso >= '"+formato.format((Date)selector_fecha_inicial.getModel().getValue())+"'";
            if(jchkFechaFinal.isSelected())
                filtro+=(filtro.equals("")?" WHERE":" AND")+" b.fecha_clausura <= '"+formato.format((Date)selector_fecha_final.getModel().getValue())+" 23:59:0'";
            formato=null;
        }
        CardarDatos(filtro);
    }
    private void jtfUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfUsuarioKeyTyped
        modelo.removeAllElements();
        JTable tabla = Conexion.ObtenerTabla("SELECT id_usuario,CONCAT_WS(' ',nombre,apellido) FROM usuario WHERE nombre LIKE '"+Util.ComponerTexto(jtfUsuario.getText()+evt.getKeyChar())+"%' OR apellido LIKE '"+Util.ComponerTexto(jtfUsuario.getText()+evt.getKeyChar())+"%'",new String[]{"id","descripcion"});
        for (int i = 0; i < tabla.getRowCount(); i++)
            modelo.addElement(new ModeloItemValor(tabla.getValueAt(i, 1), tabla.getValueAt(i, 0)));
    }//GEN-LAST:event_jtfUsuarioKeyTyped
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        ConsultaFiltrada();
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized

    private void jtblBitacoraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblBitacoraMouseClicked
        if(jtblBitacora.getSelectedRow()>-1 && evt.getClickCount()==2 && !evt.isConsumed())
            CargarDatosDetalle(jtblBitacora.getValueAt(jtblBitacora.getSelectedRow(),0).toString());
    }//GEN-LAST:event_jtblBitacoraMouseClicked

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblBitacora.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarReporteExcel(jtblBitacora,archivo_excel,"Reporte Bitacora","SELECT accion,hora FROM detallebitacora WHERE id_bitacora=@id ORDER BY hora ASC;",new String[]{"Áccion","Hora"})){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JComboBox jcbFormulario;
    private javax.swing.JCheckBox jchkFormulario;
    private javax.swing.JList jlstUsuario;
    private javax.swing.JPanel jpFechaFinal;
    private javax.swing.JPanel jpFechaInicial;
    private javax.swing.JTable jtblBitacora;
    private javax.swing.JTable jtblDetalleBitacora;
    private javax.swing.JTextField jtfUsuario;
    // End of variables declaration//GEN-END:variables
}